package com.fengze.framework.aspectj;

import com.fengze.common.annotation.AutoSetInsertValue;
import com.fengze.common.core.domain.BaseEntity;
import com.fengze.common.core.domain.model.LoginUser;
import com.fengze.common.utils.SecurityUtils;
import com.fengze.common.utils.reflect.ReflectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class AutoSetValueAspect {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    private static final String FIELD_USER_ID = "userId";
    private static final String FIELD_DEPT_ID = "deptId";

    private static final String FIELD_CREATE_BY = "createBy";
    private static final String FILED_CREATE_TIME = "createTime";

    private static final String FIELD_UPDATE_BY = "updateBy";

    private static final String FIELD_UPDATE_TIME = "updateTime";
    private static final String FIELD_CREATE_USER_NAME = "createUserName";


    @Pointcut("@annotation(com.fengze.common.annotation.AutoSetInsertValue)")
    public void autoSetInsertValuePointCut(){

    }

    @Pointcut("@annotation(com.fengze.common.annotation.AutoSetUpdateValue)")
    public void autoSetUpdateValuePointCut(){

    }

    // 新增自动插入拦截
    @Before("autoSetInsertValuePointCut()")
    public void insertBefore(JoinPoint point) throws Throwable{

        Object args[] = point.getArgs();
        for (Object arg : point.getArgs()) {
            if(arg instanceof BaseEntity){
                setDefaultValue(arg);
            }
        }
    }

    private void setDefaultValue(Object arg) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        ReflectUtils.setFieldValue(arg,FIELD_USER_ID,loginUser.getUserId());
        ReflectUtils.setFieldValue(arg,FIELD_DEPT_ID,loginUser.getDeptId());
        ReflectUtils.setFieldValue(arg,FIELD_CREATE_BY,loginUser.getUsername());
        ReflectUtils.setFieldValue(arg,FILED_CREATE_TIME,new Date());
        ReflectUtils.setFieldValue(arg,FIELD_CREATE_USER_NAME,loginUser.getUser().getNickName());

    }

    // 修改自动插入拦截
    @Before("autoSetUpdateValuePointCut()")
    public void updateBefore(JoinPoint point) throws Throwable{
        // 获取当前的用户
        Object[] args = point.getArgs();
        for (Object arg : args) {
            if (arg instanceof BaseEntity) {
                // 获取当前的用户
                LoginUser loginUser = SecurityUtils.getLoginUser();
                ReflectUtils.setFieldValue(arg,FIELD_UPDATE_BY,loginUser.getUsername());
                ReflectUtils.setFieldValue(arg,FIELD_UPDATE_TIME,new Date());
            }
        }
    }
}
